<template>
    <view class="page over-hide column">
        <hj-navbar :title="title" />
        <!-- 内容区 -->
        <view class="flex-auto w100 pl-30 pr-30 pt-30 pb-50 over-auto-y">
            <!-- 上方状态区 -->
            <view class="header br-24 mb-24" v-if="pageStatus === 'detail'">
                <view class="align-center">
                    <text class="pr-12 ft-48 c-m">{{ statusText[invoiceForm.status] || '' }}</text>
                    <hj-image
                        v-if="invoiceForm.status !== 3"
                        :isLoad="false"
                        :src="statusIcon[invoiceForm.status]"
                        height="48rpx"
                        width="48rpx"
                        mode="aspectFit"
                    />
                </view>
                <view v-if="invoiceForm.status === 2" class="bold mt-12 ft-30">驳回原因：</view>
                <view v-if="invoiceForm.status === 2" class="c-err error-in mt-10 mb-10">
                    {{ invoiceForm.refuseReason || '无' }}
                </view>
            </view>
            <view class="main mb-24 br-24">
                <view class="info-list flex" @click="goOrder">
                    <view class="pr-20 height align-center">订单号</view>
                    <view class="flex-auto">
                        <view class="height align-center flex-end">
                            <text class="pr-8">{{ orderNo || '' }}</text>
                            <hj-image
                                style="margin-right: -6rpx"
                                :isLoad="false"
                                src="right-01.png"
                                height="26rpx"
                                width="26rpx"
                                mode="aspectFit"
                            />
                        </view>
                    </view>
                </view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">开票金额</view>
                    <view class="flex-auto">
                        <view class="height align-center c-m bold ft-24 flex-end">
                            ￥<text class="ft-36">{{ invoiceForm.amount || 0 }}</text>
                        </view>
                    </view>
                </view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">发票类型</view>
                    <view class="flex-auto">
                        <view class="height align-center flex-end">
                            <text class="pl-8">
                                {{ invoiceType[invoiceForm.invoiceType] || '普通发票' }}
                            </text>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 表单区 -->
            <view class="main br-24">
                <view v-if="pageStatus === 'detail'" class="mask-box"></view>
                <view class="bold ft-32 pt-24 pb-4">开票信息</view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">抬头类型</view>
                    <view class="flex-auto">
                        <view class="height align-center"> 企业单位 </view>
                    </view>
                </view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">公司抬头</view>
                    <view class="flex-auto">
                        <view class="height align-center">
                            <up-input
                                placeholder="必填"
                                v-model="invoiceForm.invoiceTitle"
                                fontSize="28rpx"
                                :clearable="true"
                                :maxlength="60"
                                @focus="validateForm.invoiceTitle = ''"
                            ></up-input>
                        </view>
                        <view v-if="validateForm.invoiceTitle" class="ft-24 error-msg">
                            {{ validateForm.invoiceTitle }}
                        </view>
                    </view>
                </view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">公司税号</view>
                    <view class="flex-auto">
                        <view class="height align-center">
                            <up-input
                                placeholder="必填"
                                v-model="invoiceForm.taxNo"
                                fontSize="28rpx"
                                :clearable="true"
                                :maxlength="60"
                                @focus="validateForm.taxNo = ''"
                            ></up-input>
                        </view>
                        <view v-if="validateForm.taxNo" class="ft-24 error-msg">
                            {{ validateForm.taxNo }}
                        </view>
                    </view>
                </view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">公司地址</view>
                    <view class="flex-auto">
                        <view class="height align-center">
                            <up-input
                                placeholder="选填"
                                v-model="invoiceForm.address"
                                fontSize="28rpx"
                                :clearable="true"
                                :maxlength="60"
                            ></up-input>
                        </view>
                    </view>
                </view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">公司电话</view>
                    <view class="flex-auto">
                        <view class="height align-center">
                            <up-input
                                placeholder="选填"
                                v-model="invoiceForm.companyPhone"
                                fontSize="28rpx"
                                :clearable="true"
                                :maxlength="11"
                                type="number"
                            ></up-input>
                        </view>
                    </view>
                </view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">开户银行</view>
                    <view class="flex-auto">
                        <view class="height align-center">
                            <up-input
                                placeholder="选填"
                                v-model="invoiceForm.bankAccount"
                                fontSize="28rpx"
                                :clearable="true"
                                :maxlength="20"
                            ></up-input>
                        </view>
                    </view>
                </view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">开户账号</view>
                    <view class="flex-auto">
                        <view class="height align-center">
                            <up-input
                                placeholder="选填"
                                v-model="invoiceForm.bankName"
                                fontSize="28rpx"
                                :clearable="true"
                                :maxlength="20"
                                type="number"
                            ></up-input>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 发票接受方式 -->
            <view class="main br-24 mt-24">
                <view v-if="pageStatus === 'detail'" class="mask-box"></view>
                <view class="bold ft-32 pt-24 pb-4">开票人信息</view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">电子邮箱</view>
                    <view class="flex-auto">
                        <view class="height align-center">
                            <up-input
                                placeholder="选填"
                                v-model="invoiceForm.email"
                                fontSize="28rpx"
                                :clearable="true"
                                :maxlength="60"
                                @focus="validateForm.email = ''"
                            ></up-input>
                        </view>
                        <view v-if="validateForm.email" class="ft-24 error-msg">
                            {{ validateForm.email }}
                        </view>
                    </view>
                </view>
                <view class="info-list flex">
                    <view class="pr-20 height align-center">手机号码</view>
                    <view class="flex-auto">
                        <view class="height align-center">
                            <up-input
                                placeholder="选填"
                                v-model="invoiceForm.phone"
                                fontSize="28rpx"
                                :clearable="true"
                                :maxlength="11"
                                @focus="validateForm.phone = ''"
                            ></up-input>
                        </view>
                        <view v-if="validateForm.phone" class="ft-24 error-msg">
                            {{ validateForm.phone }}
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <!-- 底部 -->
        <view class="footer">
            <view class="footer-top center pr-30 pl-30 ft-32 bold">
                <view v-if="pageStatus !== 'detail'" class="but center" @click="submit">
                    提交
                </view>
                <view
                    v-else-if="invoiceForm.status === 0"
                    class="but center but1"
                    @click="handleCancel"
                    >取消申请</view
                >
                <view v-else-if="invoiceForm.status === 1" class="but center" @click="handleLook">
                    查看发票
                </view>
                <view
                    v-else-if="[2, 3].includes(invoiceForm.status)"
                    class="but center"
                    @click="handleEdit"
                >
                    重新申请
                </view>
            </view>
            <!-- 底部安全区域 -->
            <hj-safe-footer />
        </view>
        <!-- 加载 -->
        <hj-loading :show="isInitLoad" v-if="isInitLoad" />
    </view>
</template>

<script setup>
/**
 * @description 申请开票
 * @author yinzhi
 * @date 2025-05
 */
import { onLoad } from '@dcloudio/uni-app'
import { ref, computed } from 'vue'
import { test } from '@/uni_modules/uview-plus'
import { logger } from '@/utils/log.js'
import {
    getInvoiceDetailApi,
    cancelInvoiceApi,
    applyInvoiceApi,
    updateInvoiceApi
} from '@/libs/api/orderApi.js'

// load状态
const isInitLoad = ref(false)
// 页面状态
const pageStatus = ref('apply')
// 发票ID 用于详情页
const orderNo = ref(null)
// 开票流程对应状态
const statusText = ref({
    0: '开票中',
    1: '开票成功',
    2: '开票失败',
    3: '取消申请'
})
const statusIcon = ref({
    0: 'invoice-01.png',
    1: 'invoice-02.png',
    2: 'invoice-03.png'
})
const invoiceType = {
    1: '普通发票',
    2: '增值税专用发票'
}
// 发票表单
const invoiceForm = ref({
    id: null, //发票ID
    invoiceTitle: '', //发票抬头
    taxNo: '', //税号
    address: '', //公司店址
    bankName: '', //开户行
    bankAccount: '', //银行账号
    companyPhone: '', //公司电话
    email: '', //开票人邮箱
    phone: '', //开票人手机
    amount: 0, //开票金额
    invoiceType: 1, //发票类型
    refuseReason: '', //驳回原因
    invoiceUrl: '' //发票地址
})

// 验证信息
const validateForm = ref({
    invoiceTitle: '',
    taxNo: '',
    email: '',
    phone: ''
})

// 头部标题
const title = computed(() => {
    let text = {
        apply: '申请开票',
        detail: '发票详情',
        edit: '重新编辑'
    }
    return text[pageStatus.value] || '申请开票'
})

// 页面加载时执行
onLoad(async e => {
    if (e.amount) {
        invoiceForm.value.amount = Number(e.amount)
    }
    if (e.orderNo) {
        orderNo.value = e.orderNo
    }
    // 判断页面申请，查看详情状态
    if (e.type) {
        pageStatus.value = e.type
        // 如果页面时查看详情也要获取发票详情信息
        if (pageStatus.value === 'detail') {
            isInitLoad.value = true
            getDetail()
        }
    }
})

// 如果是详情页面则需要获取发票详情信息接口
const getDetail = async () => {
    try {
        const data = await getInvoiceDetailApi({
            orderNo: orderNo.value
        })
        invoiceForm.value = data
        pageStatus.value = 'detail'
        // 关闭加载动画
        let time = setTimeout(() => {
            isInitLoad.value = false
            clearTimeout(time)
        }, 800)
    } catch (error) {
        logger.error('[getDetail] 获取发票失败:', error)
    }
}

// 取消申请 需要调用取消接口
const handleCancel = async () => {
    if (!invoiceForm.value?.id) return
    try {
        await cancelInvoiceApi({
            id: invoiceForm.value.id
        })
        uni.showToast({
            title: '取消成功',
            icon: 'none',
            mask: true
        })
        await getDetail()
        // 更新发票列表的
        uni.$emit('initList', {
            orderNo: orderNo.value,
            status: invoiceForm.value.status
        })
        // 更新订单列表或者订单详情的
        uni.$emit('upDataOrder', {
            orderNo: orderNo.value
        })
    } catch (error) {
        logger.error('[getDetail] 获取发票失败:', error)
    }
}

//新申请
const applyInvoice = async () => {
    try {
        await applyInvoiceApi({
            orderNo: orderNo.value,
            ...invoiceForm.value
        })
        uni.showToast({
            title: '提交成功',
            icon: 'none',
            mask: true
        })
        uni.$emit('upDataOrder', {
            orderNo: orderNo.value
        })
        await getDetail()
    } catch (error) {
        logger.error('[getDetail] 申请发票失败:', error)
    }
}
// 发票编辑
const updateInvoice = async () => {
    try {
        await updateInvoiceApi({
            orderNo: orderNo.value,
            ...invoiceForm.value
        })
        uni.showToast({
            title: '提交成功',
            icon: 'none',
            mask: true
        })
        await getDetail()
        uni.$emit('initList', {
            orderNo: orderNo.value,
            status: invoiceForm.value.status
        })
    } catch (error) {
        logger.error('[updateInvoiceApi] 编辑发票失败:', error)
    }
}

// 提交表单发票
const submit = async () => {
    if (invoiceForm.value.invoiceTitle === '') {
        validateForm.value.invoiceTitle = '请填写公司抬头'
    } else if (invoiceForm.value.invoiceTitle.length < 2) {
        validateForm.value.invoiceTitle = '请填写正确的公司抬头'
    }
    if (invoiceForm.value.taxNo === '') {
        validateForm.value.taxNo = '请填写公司税号'
    } else if (!test.enOrNum(invoiceForm.value.taxNo)) {
        validateForm.value.taxNo = '请填写正确的公司税号'
    }

    if (invoiceForm.value.email && !test.email(invoiceForm.value.email)) {
        validateForm.value.email = '请填写正确的电子邮箱'
    }
    if (invoiceForm.value.phone && !test.mobile(invoiceForm.value.phone)) {
        validateForm.value.phone = '请填写正确的手机号码'
    }
    // 使用 Object.values 和 some 方法判断是否有验证信息不为空
    if (Object.values(validateForm.value).some(value => value)) {
        return
    }
    if (pageStatus.value === 'apply') {
        await applyInvoice()
    } else if (pageStatus.value === 'edit') {
        await updateInvoice()
    }
}

// 重新编辑
const handleEdit = () => {
    pageStatus.value = 'edit'
}

// 查看订单 isInvoice通知页面是发票详情页面过去的 防止页面再次点击查看发票详情的时候 会进页面死循环
const goOrder = () => {
    if (!orderNo.value) return
    uni.navigateTo({
        url: `/pages/order/order-details/index?orderNo=${orderNo.value || ''}&isInvoice=true`
    })
}

// 查看发票
const handleLook = () => {
    if (!invoiceForm.value?.invoiceUrl) {
        return uni.showToast({
            title: '暂无发票图片',
            icon: 'none',
            mask: true
        })
    }
    // 预览图片事件
    uni.previewImage({
        showmenu: true, //微信小程序专有
        current: invoiceForm.value.invoiceUrl,
        urls: [invoiceForm.value.invoiceUrl]
    })
}
</script>

<style scoped lang="scss">
:deep(.u-input) {
    padding: 0 !important;
}
.main {
    background: $uni-bg-color;
    padding: 0 30rpx;
    position: relative;
    box-shadow: 0 0 10rpx 0 rgba($color: #000000, $alpha: 0.08);
    .mask-box {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        z-index: 90;
    }
    .info {
        &-list {
            border-bottom: 1px solid $uni-bg-color-hover;
            .height {
                height: 96rpx;
            }
        }
        &-list:last-child {
            border: none;
        }
    }
    .error-msg {
        border-bottom: 1px solid $uni-color-error;
        color: $uni-color-error;
        margin-top: -10rpx;
    }
}
.header {
    background: $uni-bg-color;
    padding: 20rpx 30rpx;
    box-shadow: 0 0 10rpx 0 rgba($color: #000000, $alpha: 0.08);
    .error-in {
        background: $uni-bg-color-grey;
        padding: 14rpx 20rpx;
        border-radius: 12rpx;
    }
}
.footer {
    background: $uni-bg-color;
    box-shadow: 0 0 10rpx 0 rgba($color: #000000, $alpha: 0.08);
    position: relative;
    z-index: 20;
    &-top {
        height: 120rpx;
        .but {
            height: 88rpx;
            width: 100%;
            border-radius: 44rpx;
            background: $uni-color-primary;
            border: 1px solid $uni-color-primary;
            color: #fff;
        }
        .but1 {
            border-color: $uni-color-success;
            background: none;
            color: $uni-color-success;
        }
    }
}
.page {
    background: $uni-bg-color-grey;
}
</style>
